<?php
/**
 *
 * 导出 excel 表格，通用服务类
 * ExportXlsxService.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-04-06 09:40:19
 * @modified    2023-04-06 09:40:19
 *
 */

namespace App\Services;

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ExportXlsxService
{
    /**
     * titles: [{title: 标题, count: 合并多少列}]
     */
    private $titles;
    private $columnHeads;
    private $mainData;

    public function __construct($titles, $columnHeads, $mainData)
    {
        $this->titles = $titles;
        $this->columnHeads = $columnHeads;
        $this->mainData = $mainData;
    }

    /**
     * 导出excel: 生成并返回 excel 文件
     *
     * @param $fileName
     */
    public function export($fileName)
    {
        $pathPrefix = 'downloads/' . trim($fileName) . '/' . date('Y/m/d');
        $prefix = public_path() . '/' . $pathPrefix;
        $excelFileName = "{$fileName}-" . md5(date('YmdHis') . microtime()) . '.xlsx';
        if (!is_dir($prefix)) {
            mkdir($prefix, 0777, true);
        }
        $excelFilePath = $prefix . '/' . $excelFileName;
        $spreadsheet = new Spreadsheet();
        $sheet = new Worksheet($spreadsheet, $fileName);
        $spreadsheet->addSheet($sheet);
        $spreadsheet->removeSheetByIndex(0);

        $titles = $this->titles;
        $titleArr = [];
        $combineArr = [];
        if ($titles) {
            $start = 1;
            foreach ($titles as $item) {
                $end = $start + $item['count'] - 1;
                for ($i = 0; $i < $item['count']; $i++) {
                    $titleArr[] = $item['title'];
                }
                $combineArr[] = [
                    'start' => $start,
                    'end' => $end
                ];
                $start += $item['count'];
            }
        }
        $excelData = [];
        if ($titleArr) {
            $excelData[] = $titleArr;
        }
        $excelData[] = $this->columnHeads;

        // main data
        $mainData = $this->mainData;
        $excelData = array_merge($excelData, $mainData);
        $sheet->fromArray($excelData);
        if ($combineArr) {
            foreach ($combineArr as $item) {
                $itemStart = $item['start'];
                $itemEnd = $item['end'];
                $startColumnName = Coordinate::stringFromColumnIndex($itemStart);
                $endColumnName = Coordinate::stringFromColumnIndex($itemEnd);
                $itemStartCell = "{$startColumnName}1";
                $itemEndCell = "{$endColumnName}1";
                // 合并单元格
                $sheet->mergeCells("{$itemStartCell}:{$itemEndCell}");
            }
        }
        $writer = new Xlsx($spreadsheet);
        $writer->save($excelFilePath);
        return env('APP_URL') . '/' . $pathPrefix . '/' . $excelFileName;
    }
}